package utils

import (
	"alertmanagerWebhook/global"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

const (
	wechatTokenKey = "wechat_access_token"
	tokenExpire    = 7200 // 2小时有效期
)

// 获取企业微信access_token
func GetWeChatAccessToken() (string, error) {
	// 创建RedisUtil实例
	redisUtil, err := NewRedisUtil()
	if err != nil {
		return "", fmt.Errorf("创建RedisUtil失败: %v", err)
	}
	defer redisUtil.Close()

	// 先从redis获取
	token, err := redisUtil.HGet(wechatTokenKey, "token")
	if err == nil && token != "" {
		return token, nil
	}

	// 重新获取token
	corpID := global.Config.QyWeChat.CorpID
	corpSecret := global.Config.QyWeChat.CorpSecret
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpID, corpSecret)

	resp, err := http.Get(url)
	if err != nil {
		return "", fmt.Errorf("获取access_token失败: %v", err)
	}
	defer resp.Body.Close()

	var result struct {
		Errcode     int    `json:"errcode"`
		Errmsg      string `json:"errmsg"`
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
	}

	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return "", fmt.Errorf("解析access_token响应失败: %v", err)
	}

	if result.Errcode != 0 {
		return "", fmt.Errorf("获取access_token错误: %s", result.Errmsg)
	}

	// 存入redis，设置过期时间比实际有效期短5分钟
	err = redisUtil.HSet(wechatTokenKey, "token", result.AccessToken)
	if err != nil {
		return "", fmt.Errorf("保存access_token到redis失败: %v", err)
	}

	// 设置过期时间
	err = redisUtil.Expire(wechatTokenKey, tokenExpire-300)
	if err != nil {
		return "", fmt.Errorf("设置token过期时间失败: %v", err)
	}

	return result.AccessToken, nil
}

func ConvertMobilesToUserIDs(mobiles []string) ([]string, error) {
	var userIDs []string

	// 获取access_token
	accessToken, err := GetWeChatAccessToken()
	if err != nil {
		return nil, fmt.Errorf("获取access_token失败: %v", err)
	}

	for _, mobile := range mobiles {
		url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=%s", accessToken)

		reqBody := map[string]string{"mobile": mobile}
		jsonData, _ := json.Marshal(reqBody)

		resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		if err != nil {
			return nil, err
		}
		defer resp.Body.Close()

		var result struct {
			Errcode int    `json:"errcode"`
			Errmsg  string `json:"errmsg"`
			UserID  string `json:"userid"`
		}

		if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
			return nil, err
		}

		if result.Errcode != 0 {
			return nil, fmt.Errorf(result.Errmsg)
		}

		userIDs = append(userIDs, result.UserID)
	}

	return userIDs, nil
}
